package com.example.demo.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.annotation.JoinField;
import com.example.demo.entity.User;
import com.example.demo.view.ModelItem;
import com.example.demo.view.el.ElDatePicker;
import com.example.demo.view.el.ElType;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GlobalUtil {

    public static Map<String, Class> mapperClassMap = new HashMap<>();

    public static Map<String, Class> entityClassMap = new HashMap<>();

    public static Map<String, JSONArray> viewMap = new HashMap<>();


    public static JSONArray toViewJson(Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        JSONArray jsonArray = new JSONArray();
        for (Field field : fields) {
            fieldToView(field, jsonArray, clazz, false);
        }
        return jsonArray;
    }

    public static void fieldToView(Field field, JSONArray jsonArray, Class clazz, Boolean isJoin) {
        //TODO 过滤ID Ignore
        if (field.getName().equals("id")) {
            return;
        }
        JoinField joinField = field.getAnnotation(JoinField.class);
        if (joinField != null) {//是连接子类
            Class zz = field.getType();
            for (Field f : zz.getDeclaredFields()) {
                fieldToView(f, jsonArray, zz, true);
            }
        } else {
            JSONObject json = getAutoJson(field);
            ModelItem item = field.getAnnotation(ModelItem.class);
            if (item == null) return;
            for (Method method : ModelItem.class.getDeclaredMethods()) {
                try {
                    if (!method.invoke(item).equals("")) {
                        json.put(method.getName(), method.invoke(item));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            if (isJoin) {
                json.put("entity", StringUtils.uncapitalize(clazz.getSimpleName()));
                json.put("disabled",true);
                json.put("required", false);
            }
            jsonArray.add(json);
        }
    }


    public static JSONObject getAutoJson(Field field) {
        JSONObject json = new JSONObject();
        if (field.getType() == Date.class) {
            json.put("type", ElType.DATEPICKER);
            json.put("picker", ElDatePicker.DATE);
        } else {
            json.put("type", ElType.INPUT);
        }
        json.put("name", field.getName());
        return json;
    }

    public static void main(String[] args) {
        JSONArray jsonArray = toViewJson(User.class);
        System.out.println(jsonArray);
    }


}
